from fastapi import APIRouter, Depends, Request, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from ..database import get_db
from ..models.account import Environment
from fastapi.templating import Jinja2Templates
from datetime import datetime

router = APIRouter(prefix="/environments")
templates = Jinja2Templates(directory="app/templates")

@router.get("/")
async def list_environments(
    request: Request,
    db: Session = Depends(get_db),
    page: int = 1,
    size: int = 10,
    search: Optional[str] = None
):
    query = db.query(Environment)
    
    if search:
        query = query.filter(
            Environment.name.ilike(f"%{search}%") |
            Environment.browser_id.ilike(f"%{search}%")
        )
    
    total = query.count()
    environments = query.offset((page - 1) * size).limit(size).all()
    
    return templates.TemplateResponse(
        "environment/list.html",
        {
            "request": request,
            "environments": environments,
            "total": total,
            "page": page,
            "size": size,
            "title": "环境管理"
        }
    )

@router.post("/api")
async def create_environment(name: str, browser_id: str, remarks: Optional[str] = None, db: Session = Depends(get_db)):
    env = Environment(
        name=name,
        browser_id=browser_id,
        remarks=remarks
    )
    db.add(env)
    try:
        db.commit()
        db.refresh(env)
        return {"success": True, "data": env}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))

@router.put("/api/{env_id}")
async def update_environment(
    env_id: int,
    name: str,
    browser_id: str,
    status: bool,
    remarks: Optional[str] = None,
    db: Session = Depends(get_db)
):
    env = db.query(Environment).filter(Environment.id == env_id).first()
    if not env:
        raise HTTPException(status_code=404, detail="Environment not found")
    
    env.name = name
    env.browser_id = browser_id
    env.status = status
    env.remarks = remarks
    env.updated_at = datetime.utcnow()
    
    try:
        db.commit()
        db.refresh(env)
        return {"success": True, "data": env}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e))

@router.delete("/api/{env_id}")
async def delete_environment(env_id: int, db: Session = Depends(get_db)):
    env = db.query(Environment).filter(Environment.id == env_id).first()
    if not env:
        raise HTTPException(status_code=404, detail="Environment not found")
    
    try:
        db.delete(env)
        db.commit()
        return {"success": True}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=400, detail=str(e)) 